﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Linq.Expressions;

namespace Jmr.Core
{
	public static class ExtensionMethods
	{
		public static void NotifyPropertyChanged<TEntity>(this TEntity entity, Expression<Func<TEntity, object>> propertySelector, PropertyChangedEventHandler propertyChanged)
			where TEntity : INotifyPropertyChanged
		{
			NotifyPropertyChanged(entity, FormatPropertyName(propertySelector), propertyChanged);
		}

		public static void NotifyPropertyChanged<TEntity>(this TEntity entity, string propertyName, PropertyChangedEventHandler propertyChanged)
			where TEntity : INotifyPropertyChanged
		{
			if (propertyChanged != null)
			{
				propertyChanged(entity, new PropertyChangedEventArgs(propertyName));

			  if (entity is Jmr.Validation.Validatable)
			    propertyChanged(entity, new PropertyChangedEventArgs("Error"));
			}
		}

		static string FormatPropertyName<TEntity>(Expression<Func<TEntity, object>> propertySelector)
		{
			var lambdaString = propertySelector.ToString();
			var ret = lambdaString.Substring(lambdaString.IndexOf('.') + 1).Replace(")", string.Empty);
			return ret;

			//var memberExpression = propertySelector.Body as MemberExpression;
			//return memberExpression.Member.Name;
		}
	}
}
